﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using CourseSystem.Core.Entities;
using CourseSystem.Core.SqlServerDAL;

namespace CourseSystem.Core.BLL
{
    public class AttachmentsBLL
    {
        public static bool Add(AttachmentsInfo info)
        {
            using (var dal = new AttachmentsDAL(Settings.ConnectionName))
            {
                return dal.Add(info) != null;
            }
        }

        public static bool Edit(List<AttachmentsInfo> info)
        {
            using (var dal = new AttachmentsDAL(Settings.ConnectionName))
            {
                return dal.Update(info) != null;
            }
        }

        public static bool DelFileByRanStr(string str)
        {
            var list = GetByRanStr(str);
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.FileName))
                    File.Delete(HttpContext.Current.Server.MapPath("~/")+ item.FileName);
            }
            return DelByRanStr(str);
        }

        public static bool DelFileByList(List<AttachmentsInfo> list)
        {
            foreach (var item in list)
            {
                if (!string.IsNullOrEmpty(item.FileName))
                    File.Delete(HttpContext.Current.Server.MapPath("~/") + item.FileName);
            }
            using (var dal = new AttachmentsDAL(Settings.ConnectionName))
            {
                return dal.Delete(list) != null;
            }
        }

        public static List<AttachmentsInfo> GetByExpress(Expression<Func<AttachmentsInfo, bool>> expression)
        {
            using (var dal = new AttachmentsDAL(Settings.ConnectionName))
            {
                return dal.Select(expression);
            }
        }

        public static bool DelFileByExpress(Expression<Func<AttachmentsInfo, bool>> expression)
        {
            using (var dal = new AttachmentsDAL(Settings.ConnectionName))
            {
                var list = dal.Select(expression);
                return DelFileByList(list);
            }
        }

        public static List<AttachmentsInfo> GetByRanStr(string str)
        {
            using (var dal = new AttachmentsDAL(Settings.ConnectionName))
            {
                return dal.Select(o => o.RanSign == str);
            }
        }

        private static bool DelByRanStr(string str)
        {
            using (var dal = new AttachmentsDAL(Settings.ConnectionName))
            {
                return dal.Delete(o => o.RanSign == str) != null;
            }
        }
    }
}
